import Layout from "@/layout/index.vue";
import { flatArray } from "@/common/utils/handle-array";
// 引入 lodash 库
import cloneDeep from "lodash/cloneDeep";

/** 处理路由、菜单、权限 */
export const useRouters = () => {
  /** 自动导入全部动态路由,除了 remaining.js 文件 */
  const modules = import.meta.glob(
    ["@/router/modules/**/*.js", "!@/router/modules/**/remaining.js"],
    {
      eager: true,
    }
  );

  /** 初始空路由 */
  const routes = [];

  /** 临时路由，用于生成权限路由 */
  const temporaryRoutes = [];

  /** 初始菜单 */
  const menuList = [];

  /** 权限路由 */
  let dynamicList = [];

  /** 权限菜单 */
  let dynamicMenuList = [];

  /** 权限列表 */
  let permissionList = [];

  /** 所有modules文件下的动态路由,除了 remaining.js 文件 */
  Object.keys(modules).forEach((key) => {
    routes.push(cloneDeep(...modules[key].default));
    temporaryRoutes.push(cloneDeep(...modules[key].default));
  });

  /** 遍历所有路由,与routes分开，防止动态路由改变菜单以及权限树 */
  temporaryRoutes.forEach((item) => {
    /** 注入Layout组件，形成二级路由 */
    item.component = Layout;
  })

  /** 遍历所有路由 */
  routes.forEach((item) => {
    /** 注入Layout组件，形成二级路由 */
    item.component = Layout;
    /** 递归处理路由，形成菜单 */
    if (item.meta && item.children && item.children.length > 0)
      menuList.push(item);
    if (!item.meta && item.children && item.children.length > 0)
      menuList.push(...item.children);
  });
  menuList.sort((a, b) => a.meta.sort - b.meta.sort); // 升序

  let roleList = [];
  if (JSON.parse(localStorage.getItem("user"))) {
    roleList = JSON.parse(
      JSON.parse(localStorage.getItem("user")).role.roleJson
    );
    roleList = [...new Set(roleList.map((item) => item.split(":")[0]))];
  }

  /**
   * 构造一级路由
   * @param {*} data
   * @returns
   */
  const markFirstRoute = (data) => {
    return data.find((item) => {
      if (item.children && item.children.length > 0) {
        markFirstRoute(item.children);
      }
      return roleList.includes(item.path);
    });
  };

  /**
   * 构造下级路由
   * @param {*} data
   * @returns
   */
  const markRouteLow = (data) => {
    return data.filter((item) => {
      if (item.children && item.children.length > 0) {
        item.children = markRouteLow(item.children);
      }
      return roleList.includes(item.path);
    });
  };

  temporaryRoutes.forEach((item) => {
    if (item.children && item.children.length > 0) {
      const find = markFirstRoute(item.children);
      if (find) dynamicList.push(item);
    }
  });
  markRouteLow(dynamicList);
  dynamicMenuList = cloneDeep(dynamicList);
  // 注入首页
  dynamicMenuList.unshift(menuList[0]);
  dynamicMenuList.sort((a, b) => a.meta.sort - b.meta.sort); // 升序

  /**
   * 制造权限树(包括按钮权限)
   * @param {*} data 菜单列表及全部子菜单
   */
  const markPermissionList = (data) => {
    return data.map((item) => {
      item.label = item.meta.title;
      delete item.name;
      delete item.component;
      delete item.redirect;
      delete item.meta;
      if (item.children && item.children.length > 0) {
        markPermissionList(item.children);
      } else {
        item.children = markOnlyButtonPermission(item);
      }
      return item;
    });
  };

  /**
   * 制造按钮唯一权限标识
   * @param {*} val 最后一级菜单
   */
  const markOnlyButtonPermission = (val) => {
    const data = []
    flatArray(menuList).forEach((item) => {
      if (item.meta.permission) {
        if (item.path === val.path) {
          item.meta.permission.forEach((permissionItem) => {
            permissionItem.path = val.path + ":" + permissionItem.path;
          })
          data.push(...item.meta.permission)
        }
      }
    });
    return data
  };

  // 赋值权限列表并去掉首页
  permissionList = markPermissionList(cloneDeep(menuList)).splice(1);

  return {
    /** 菜单 */
    menuList,
    /** 权限路由 */
    dynamicList,
    /** 权限菜单 */
    dynamicMenuList,
    /** 权限树 */
    permissionList,
  };
};
